import socket
import threading
import time
class UDPClient:
    def __init__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.server_address = None
        self.callback = None

    def connect_to_server(self, server, port):
        self.server_address = (server, port)

    def stop(self):
        self.sock.close()

    def send_udp_msg(self, msg):
        if isinstance(msg, str):
            self.sock.sendto(msg.encode(), self.server_address)
        else:
            self.sock.sendto(str(msg).encode(), self.server_address)

    def set_callback(self, cb):
        self.callback = cb
        self.sock.setblocking(False)
        self.sock.settimeout(10)
        threading.Thread(target=self.recv).start()

    def recv(self):
        while True:
            try:
                data, addr = self.sock.recvfrom(1024)
                self.callback(data.decode())
            except socket.timeout:
                pass
            except KeyboardInterrupt:
                self.stop()
            except socket.error as e:
                if e.errno == socket.errno.EWOULDBLOCK:
                    print("e.error",e)
                else:
                    raise e
            time.sleep(0.05)
        
        